package com.mec.web.y2012.coreservlet;

import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;

import com.mec.beans.y2012.coreservlet.DBInfoBean;

public class DriverUtilities {
	public static final String MYSQL = "MYSQL";
	public static final String MSACCESS = "MSACCESS";
	public static final String ORACLE = "ORACLE";
	
	protected static Map<String, DBInfoBean> driverMap = new HashMap<String, DBInfoBean>();
	
	public static void loadDrivers(){
		String vendor, description, driverClass, url;
		DBInfoBean info = null;
		
		vendor = MYSQL;
		description = "MySql Connector/J 5.1";
		driverClass = "com.mysql.jdbc.Driver";
		url = "jdbc:mysql://$[host]:3306/$[dbName]";
		info = new DBInfoBean(vendor, description, driverClass, url, "scott", "tiger");
		addDriverInfoBean(info);
	}
	
	public static void addDriverInfoBean(DBInfoBean driverInfo){
		driverMap.put(driverInfo.getVendor().toUpperCase(), driverInfo);
	}
	
	public static boolean isValidVendor(String vendor){
		DBInfoBean info = driverMap.get(vendor.toUpperCase());
		return null != info	;
	}
	
	public static String makeURL(String host, String dbName, String vendor){
		DBInfoBean info = driverMap.get(vendor.toUpperCase());
		if(null == info){
			return null;
		}
		
		//
		StringBuffer url = new StringBuffer(info.getUrl());
		replace(url, "$[host]", host);
		replace(url, "$[dbName]", dbName);
		//
		return url.toString();
	}
	
	public static String getDriver(String vendor){
		DBInfoBean info =
				(DBInfoBean) driverMap.get(vendor.toUpperCase());
		//
		if(null == info){
			return null;
		}else{
			return info.getDriverClass();
		}
	}
	
	public static DBInfoBean getDriverInfo(String vendor){
		return driverMap.get(vendor.toUpperCase());
	}
	
	private static void replace(StringBuffer buffer, String match, String value){
		int index = buffer.toString().indexOf(match);
		if(0 < index){
			buffer.replace(index, index + match.length(), value);
		}
	}
	private static final Logger logger = 
			Logger.getLogger(DriverUtilities.class);

}
